<?php

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChCtrlRoomFilterRuleMapper;
use App\CustHub\Model\ChContact;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Mine\Abstracts\AbstractService;
use function FriendsOfHyperf\Lock\lock;

class ChCtrlRoomFilterRuleService extends AbstractService
{
    public $mapper;

    public function __construct(ChCtrlRoomFilterRuleMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function findByMainUid(int $mainUid): \App\CustHub\Model\ChCtrlRoomFilterRule|\Hyperf\Database\Model\Builder|null
    {
        $info = $this->mapper->findByMainUid($mainUid);
        if(empty($info)){
            return null;
        }

        $customer_filter = $info->customer_filter ?? [];
        if(!empty($customer_filter) && $customer_filter['robot_type'] == 1 && $customer_filter['filter_type'] == 0 && !empty($customer_filter['in_sys_cnf'])){
            $user_list = ChContact::query()
                ->select(['id','nickname','avatar','user_id'])
                ->where('main_uid',$mainUid)
                ->whereIn('user_id', $customer_filter['in_sys_cnf'])
                ->groupBy('user_id')
                ->get();
            $customer_filter['user_list'] = $user_list;
        }else{
            $customer_filter['user_list'] = [];
        }
        $info->customer_filter = $customer_filter;
        return $info;
    }

    public function saveRule(array $data): bool
    {
        $lock = lock('ctrl_room_filter_rule_lock:'.$data['main_uid']);
        try {
            $lock->block(2);
            $info = $this->mapper->findByMainUid($data['main_uid']);
            if(empty($info)){
                $this->mapper->save($data);
            }else{
                $this->mapper->update($info->id,$data);
            }
            $this->mapper->cleanCache($data['main_uid']);
            return true;
        }catch (LockTimeoutException $e){
            return false;
        }finally{
            $lock->release();
        }
    }
}